<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\AdminUserModel;
use App\Models\yb\CouponModel;
use App\Models\yb\PointsGoodsModel;
use App\Models\yb\UserWalletRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\GoodsOrderModel;
use App\Models\yb\ExchangeGoodsOrderModel;
use App\Models\yb\GoodsTypeModel;
use App\Models\yb\PointsGoodsTypeModel;
use App\Models\yb\UserAddressModel;
use App\Models\yb\UserCouponModel;
use App\Models\yb\GoodsContentModel;
use App\Models\yb\UserModel;
use App\Models\yb\UserWaterTicketModel;
use Illuminate\Http\Request;

class IntegralController extends Controller
{

    /**
     * Get a JWT via given credentials.
     * 积分兑换优惠券列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function CouponListing(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $data = CouponModel::where(['status'=>1,'distribution_type'=>2])->orderBy('created_at','desc')->skip(($page - 1) * $take)->take($take)->get();

        foreach($data as $key=>$val){

            if($val['validity_end']<date('Y-m-d',time())){
                unset($data[$key]);
                continue;
            }else{
                $user_coupon_data = UserCouponModel::where(['user_id'=>$user_data['id'],'coupon_id'=>$val['id'],'type'=>1])->select(['is_used'])->first();
                if(!empty($user_coupon_data)){
                    if($user_coupon_data['is_used'] == 0){
                        $data[$key]['status'] = 2; //未使用
                    }else{
                        $data[$key]['status'] = 3; //已使用
                    }
                    $data[$key]['is_exchange'] = 1;
                }else{
                    $data[$key]['is_exchange'] = 0;

                }
            }

        }

        $list = array();

        foreach($data as $key=>$val){
            $list[] = $val;
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$list]);
    }

    /**
     * Get a JWT via given credentials.
     *
     *  积分兑换商品列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsListing(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $goods_points_type = $request->post('goods_points_type', 0);

        $is_my_exchange = $request->post('is_my_exchange', 0);

        $min_integral = $request->post('min_integral', 0);

        $max_integral = $request->post('max_integral', 0);

        $order_by = $request->post('order_by');
        if($order_by == ""){
            $order_by = "created_at";
        }

        $goods_data = PointsGoodsModel::where(['status'=>1])
            ->when($goods_points_type,function($query,$goods_points_type){
                return  $query->where(['goods_points_type'=>$goods_points_type]);
            })->when($is_my_exchange,function($query,$is_my_exchange)use($user_data){
                return  $query->where('goods_price','<=',$user_data['surplus_points']);
            })->when($min_integral,function($query,$min_integral){
                return  $query->where('goods_price','>=',$min_integral);
            })->when($max_integral,function($query,$max_integral){
                return  $query->where('goods_price','<=',$max_integral);
            })->orderBy($order_by,'desc')
            ->skip(($page - 1) * $take)
            ->take($take)
            ->get();

        foreach($goods_data as $key=>$val){
            $goods_data[$key]['goods_cover'] = env('OSS_URL').$goods_data[$key]['goods_cover'];
        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$goods_data]);

    }

    /**
     * Get a JWT via given credentials.
     *
     *  分类列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsTypeListing(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        $goods_data = PointsGoodsTypeModel::skip(($page - 1) * $take)
            ->take($take)
            ->get();

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$goods_data]);

    }

      /**
     * Get a JWT via given credentials.
     *  商品详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsDetail(Request $request){

        $id = $request->post('id');

        if(empty($id)){
            return response()->json(['code'=>'201','msg' => '请选择商品']);
        }

        $goods_data = PointsGoodsModel::where(['id'=>$id])->first();

        $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
        $goods_data['goods_type_name'] = GoodsTypeModel::selectValue('id',$goods_data['goods_type']);
        $goods_banner = $goods_data['goods_banner'];
        for($i=0;$i<count($goods_banner);$i++){
            $goods_banner[$i] = env('OSS_URL').$goods_banner[$i];
        }
        $goods_data['goods_banner'] = $goods_banner;
        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$goods_data]);
    }

     /**
     * Get a JWT via given credentials.
     *  兑换优惠券
     * @return \Illuminate\Http\JsonResponse
     */
    public function CouponExchange(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $coupon_id = $request->post('coupon_id');

        if(empty($coupon_id)){
            return response()->json(['code'=>'201','msg' => '请选择要兑换的优惠券']);
        }

        $coupon_data = CouponModel::where('id',$coupon_id)->first();

        if($coupon_data['distribution_type'] != 2 || $coupon_data['validity_end']<date('Y-m-d',time()) || $coupon_data['status'] != 1){
            return response()->json(['code'=>'201','msg' => '该优惠券已过期或已下架']);
        }

        if($user_data['surplus_points']<$coupon_data['required_points']){
            return response()->json(['code'=>'201','msg' => '您的积分不足']);
        }

        CouponModel::where('id',$coupon_id)->increment('received_number');

        UserCouponModel::insert([
            'user_id' => $user_data['id'],
            'openid' => $openid,
            'goods_type' => $coupon_data['goods_type'],
            'coupon_id' => $coupon_data['id'],
            'status' => $coupon_data['status'],
            'validity_start' => date('Y-m-d'),
            'validity_end' => date('Y-m-d',strtotime("+".$coupon_data['validity_after']." day")),
            'promotion_full' => $coupon_data['promotion_full'],
            'promotion_reduce' => $coupon_data['promotion_reduce'],
            'type' => 1,
            'created_at' => date('Y-m-d H:i:s',time())
        ]);

       UserModel::where(['id'=>$user_data['id']])->update([
            'surplus_points' => $user_data['surplus_points']-$coupon_data['required_points'],
        ]);
        UserWalletRecordModel::insert([
            'user_id'=>$user_data['id'],
            'openid'=>$user_data['openid'],
            'phone'=>$user_data['phone'],
            'avatar'=>$user_data['avatar'],
            'nickname'=>$user_data['nickname'],
            'amount'=>$coupon_data['required_points'],
            'status'=>0,
            'remark'=>'兑换优惠券',
            'created_at'=>date('Y-m-d H:i:s',time())
        ]);

        return response()->json(['code'=>'200','msg' => '兑换成功']);
    }

     /**
     * Get a JWT via given credentials.
     *  积分兑换商品
     * @return \Illuminate\Http\JsonResponse
     */
    public function GoodsExchange(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $points_goods_id = $request->post('points_goods_id');

        if(empty($points_goods_id)){
            return response()->json(['code'=>'201','msg' => '请选择要兑换的商品']);
        }

        $address_id = $request->post('address_id');

        if(empty($address_id)){
            return response()->json(['code'=>'201','msg' => '请选择收货地址']);
        }

        $points_goods_data = PointsGoodsModel::where('id',$points_goods_id)->first();

        if(empty($points_goods_data) || $points_goods_data['goods_stock']<1 || $points_goods_data['status'] != 1){
            return response()->json(['code'=>'201','msg' => '商品库存不足或已下架']);
        }

        if($user_data['surplus_points']<$points_goods_data['goods_price']){
            return response()->json(['code'=>'201','msg' => '您的积分不足']);
        }

        $orderSn = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

        $insert_data = [
            'order_sn' => $orderSn,
            'user_id' => $user_data['id'],
            'openid' => $openid,
            'goods_id' => $points_goods_id,
            'address_id' => $address_id,
            'number' => 1,
            'amount' => $points_goods_data['goods_price'],
            'pay_time' => date('Y-m-d H:i:s',time()),
            'created_at' => date('Y-m-d H:i:s',time())
        ];

        ExchangeGoodsOrderModel::insert($insert_data);

        UserModel::where(['id'=>$user_data['id']])->update([
            'surplus_points' => $user_data['surplus_points']-$points_goods_data['goods_price'],
        ]);

        PointsGoodsModel::where('id',$points_goods_id)->decrement('goods_stock');

        UserWalletRecordModel::insert([
            'user_id'=>$user_data['id'],
            'openid'=>$user_data['openid'],
            'phone'=>$user_data['phone'],
            'avatar'=>$user_data['avatar'],
            'nickname'=>$user_data['nickname'],
            'amount'=>$points_goods_data['goods_price'],
            'status'=>0,
            'remark'=>'兑换商品',
            'created_at'=>date('Y-m-d H:i:s',time())
        ]);

        return response()->json(['code'=>'200','msg' => '兑换成功']);
    }

     /**
     * Get a JWT via given credentials.
     *  积分兑换商品
     * @return \Illuminate\Http\JsonResponse
     */
    public function ExchangeListing(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $type = $request->post('type',1);

        $page = $request->post('page', 1);

        $take = $request->post('take', 10);

        if($type == 1){
            $data = ExchangeGoodsOrderModel::where(['openid'=>$openid])
                ->select(['order_sn','goods_id','address_id','number','amount','status','created_at'])
                ->orderBy('created_at','desc')
                ->skip(($page - 1) * $take)
                ->take($take)
                ->get();
            foreach($data as $key=>$val){
                $goods_data = PointsGoodsModel::where('id',$val['goods_id'])->first();
                $goods_data['goods_cover'] = env('OSS_URL').$goods_data['goods_cover'];
                $data[$key]['goods_data'] = $goods_data;
            }

        }else{
            $data = UserCouponModel::where(['openid'=>$openid])
                ->select(['coupon_id','goods_type','is_used','status','usage_time','created_at'])
                ->orderBy('created_at','desc')
                ->skip(($page - 1) * $take)
                ->take($take)
                ->get();
            foreach($data as $key=>$val){
                $coupon_data = CouponModel::where('id',$val['coupon_id'])->first();
                $data[$key]['coupon_data'] = $coupon_data;
            }

        }

        return response()->json(['code'=>'200','msg' => '请求成功','data'=>$data]);
    }

     /**
     * Get a JWT via given credentials.
     *  积分兑换商品
     * @return \Illuminate\Http\JsonResponse
     */
    public function OrderConfirm(Request $request){

        $openid = $request->post('openid');

        $user_data = UserModel::where(['openid'=>$openid])->first();

        if(empty($user_data)){
            return response()->json(['code'=>'401','msg' => '请登录']);
        }

        $order_sn = $request->post('order_sn');

        $data = ExchangeGoodsOrderModel::where(['order_sn'=>$order_sn])->first();

        if(empty($data) || $data['status'] != 1){
            return response()->json(['code'=>'201','msg' => '该订单不可确认收货']);
        }

        $data = ExchangeGoodsOrderModel::where(['order_sn'=>$order_sn])->update(['status'=>2]);

        return response()->json(['code'=>'200','msg' => '请求成功']);
    }


}
